package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.events.Event;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManagerService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public PageResult findAllUsers(Integer page, Integer pagesize) {
        IPage<UserInfo> iPage = userInfoApi.findAll(page, pagesize);
        List<UserInfo> infos = iPage.getRecords();
        for (UserInfo info : infos) {
            String key = Constants.USER_FREEZE+info.getId();
            if (redisTemplate.hasKey(key)){
                info.setUserStatus("2");
            }
        }
        iPage.setRecords(infos);
        return new PageResult(page, pagesize, iPage.getTotal(), iPage.getRecords());
    }

    public UserInfo findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        String key = Constants.USER_FREEZE+userInfo.getId();
        if (redisTemplate.hasKey(key)){
            userInfo.setUserStatus("2");
        }
        return userInfo;
    }

    /**
     * 查询当前用户所有视频
     *
     * @param page
     * @param pagesize
     * @param uid
     * @return
     */
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        return videoApi.findByUserId(page, pagesize, uid);
    }

    /**
     * @param page
     * @param pagesize
     * @param uid
     * @param state
     * @return
     */
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        // 调用api查询数据
        PageResult pr = movementApi.findByUserId(uid, state, page, pagesize);
        //解析PageResult，获取movement对象数据列表
        List<Movement> items = (List<Movement>) pr.getItems();
        //将movement转换为vo对象
        if (CollUtil.isEmpty(items)) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<MovementsVo> voList = new ArrayList<>();
        for (Movement item : items) {
            UserInfo userInfo = map.get(item.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, item);
                voList.add(vo);
            }
        }
        pr.setItems(voList);
        return pr;
    }

    /**
     * 查看动态详情
     *
     * @param id
     * @return
     */
    public MovementsVo movementDetail(String id) {
        Movement movement = movementApi.movementDetails(id);
        UserInfo userinfo = userInfoApi.findById(movement.getUserId());
        if (userinfo == null) {
            throw new BusinessException("用户信息异常");
        }
        return MovementsVo.init(userinfo, movement);
    }

    /**
     * 查看评论列表
     * @param messageID
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult comments(String messageID, Integer page, Integer pagesize) {
        PageResult pr  = commentApi.findCommentByPage(messageID, CommentType.COMMENT, page, pagesize);
        List<Comment> comments = (List<Comment>) pr.getItems();
        if (comments.isEmpty()){
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<CommentVo> voList = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo!=null){
                CommentVo vo = CommentVo.init(userInfo, comment);
                voList.add(vo);
            }
        }
        pr.setItems(voList);
        return pr ;
    }

    /**
     * 用户冻结
     * @param map
     * @return
     */
    public Map freeze(Map map) {
        //构造key
        String userId = map.get("userId").toString();
        String key = Constants.USER_FREEZE+userId;
        //构造冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
        int freezingTime = Integer.parseInt(map.get("freezingTime").toString()) ;
        int days = 0;
        if (freezingTime == 1) {
            days=3;
        } else if (freezingTime == 2) {
            days=7;
        }
        //操作Redis，将冻结数据存入Redis
        String value = JSON.toJSONString(map);
        if (days>0){
            redisTemplate.opsForValue().set(key,value,days, TimeUnit.MINUTES);
        }else {
            redisTemplate.opsForValue().set(key,value);
        }
        Map retMap = new HashMap();
        retMap.put("message","冻结成功！");
        return retMap;
    }

    /**
     * 用户解冻
     * @param map
     * @return
     */
    public Map unfreeze(Map map) {
        String key = Constants.USER_FREEZE+map.get("userId").toString();
        redisTemplate.delete(key);
        Map retMap = new HashMap();
        retMap.put("message","解冻成功!");
        return retMap;
    }
}
